<script setup>
import api from '../api/billapi.js'
import {ref, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import lodash from 'lodash'
const isAdd=ref(false);
//定义绑定的数据
//表格中的数据
const tableData = ref([]);

const total=ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: '',
  room_fee: '',
  extra_fee: '',
  bill_time:'',
});

//要修改或者新增的数据
const obj = ref({});

const reseve=ref({});


const defaultImageUrl=ref('');
//上传图片相关
const uploadDialogVisible = ref(false);
const currentStaffId = ref(null);
const uploadImageUrl = ref('');


const search = async () => {
  try {
    // 清理参数，移除空值和无效值
    const params = {};
    Object.keys(searchObj.value).forEach(key => {
      if (searchObj.value[key] !== '' && searchObj.value[key] !== null && searchObj.value[key] !== undefined) {
        // 特别处理日期参数，确保格式正确
        if (key === 'bill_time') {
          // 如果是日期对象，转换为字符串格式
          if (searchObj.value[key] instanceof Date) {
            const date = searchObj.value[key];
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            params[key] = `${year}-${month}-${day} 00:00:00`;
          } else if (typeof searchObj.value[key] === 'string' && searchObj.value[key].match(/^\d{4}-\d{2}-\d{2}$/)) {
            // 如果是 YYYY-MM-DD 格式的字符串，补充时间部分
            params[key] = `${searchObj.value[key]} 00:00:00`;
          } else {
            // 其他情况直接使用
            params[key] = searchObj.value[key];
          }
        } else {
          // 确保数字类型参数是数字而不是字符串
          if (key === 'current' || key === 'limit' || key === 'user_id' || key === 'room_fee' || key === 'extra_fee') {
            params[key] = Number(searchObj.value[key]);
          } else {
            params[key] = searchObj.value[key];
          }
        }
      }
    });

    console.log('实际发送的查询参数:', params);
    var result = await api.page(params);
    console.log('API返回结果:', result);
    if (result && result.data) {
      tableData.value = result.data;
      console.log("表格数据：", tableData.value);
      // 确保total是数字类型
      total.value = Number(result.count) || 0;
      console.log("总记录数：", total.value);
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("查询出错:", error);
    tableData.value = [];
    total.value = 0;
    ElMessage.error("查询数据失败");
  }
}
//页面加载后要挂载的数据
onMounted(async () => {
  await search();
});
//定义方法

const handleSizeChange=()=>{
  search();
}
const handleCurrentChange=()=>{
  search();
}

const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
}

const resetSearch = () => {
  searchObj.value = {
    current: 1,
    limit: 10,
    user_id: '',
    room_fee: '',
    extra_fee: '',
    bill_time:''
  };
  search();
}

const save = async () => {
  try {
    // 处理提交的数据，确保日期格式正确
    const submitData = {...obj.value};
    if (submitData.bill_time instanceof Date) {
      const date = submitData.bill_time;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      submitData.bill_time = `${year}-${month}-${day} 00:00:00`;
    } else if (typeof submitData.bill_time === 'string' && submitData.bill_time.match(/^\d{4}-\d{2}-\d{2}$/)) {
      submitData.bill_time = `${submitData.bill_time} 00:00:00`;
    }

    if (isAdd.value) {
      // 新增操作
      await api.add(submitData);
      ElMessage.success("新增成功");
    } else {
      // 编辑操作
      await api.edit(submitData);
      ElMessage.success("修改成功");
    }
    await search(); // 刷新表格
    editWinVisible.value = false; // 关闭编辑对话框
  } catch (error) {
    console.error(isAdd.value ? "新增失败" : "编辑失败", error);
    ElMessage.error(isAdd.value ? "新增失败，请检查网络或数据格式" : "修改失败，请检查网络或数据格式");
  }
}

const del = (row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await api.del(row.id);
        //重新加载数据
        //设置从第一页开始查询
        searchObj.value.current = 1;
        await search();
      })
      .catch(() => {
      })
}

const handlerAdd = async () => {
  obj.value = {user_id: '', room_fee:'', extra_fee: '', bill_time: ''};
  isAdd.value=true;
  editWinVisible.value = true;
}

const edit = (row) => {
  // 处理编辑时的数据，确保日期格式正确
  const editData = lodash.clone(row);
  if (editData.bill_time && typeof editData.bill_time === 'string' && editData.bill_time.includes(' ')) {
    // 如果包含时间部分，只取日期部分
    editData.bill_time = editData.bill_time.split(' ')[0];
  }
  obj.value = editData;
  isAdd.value = false;
  editWinVisible.value = true;
}
// //图片加载失败处理
// const handleImageError = (event) => {
//   event.target.src = defaultImageUrl.value;
// };
// //打开上传图片对话框
// const openUploadDialog=(staffId)=>{
//   currentStaffId.value=staffId;
//   uploadDialogVisible.value=true;
// };
// //上传图片到数据库
// const uploadImage=async ()=>{
//   if (!uploadImageUrl.value){
//     ElMessage.error("请输入图片URL");
//     return;
//   }
//   try{
//     await api.edit({id:currentStaffId.value, imageUrl:uploadImageUrl.value})
//     ElMessage.success("图片上传成功");
//     uploadDialogVisible.value=false;
//     uploadImageUrl.value='';
//     await search();
//   }catch (error){
//     ElMessage.error("图片上传失败");
//     console.error(error);
//   }
// }


</script>

<template>
  <div class="cyber-container">
    <div class="cyber-card">
      <div class="card-header">
        <h2>账单管理</h2>
        <div class="header-actions">
          <el-button type="primary" @click="handlerAdd" class="cyber-button">
            <el-icon><Plus /></el-icon>
            新增账单
          </el-button>
        </div>
      </div>

      <div class="cyber-form-card">
        <el-form :model="searchObj" label-width="100px" class="search-form">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="用户ID">
                <el-input v-model="searchObj.user_id" placeholder="请输入用户ID" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="房间费用">
                <el-input v-model="searchObj.room_fee" placeholder="请输入房间费用" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="额外费用">
                <el-input v-model="searchObj.extra_fee" placeholder="请输入额外费用" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="账单时间">
                <el-date-picker
                  v-model="searchObj.bill_time"
                  type="date"
                  placeholder="请选择账单时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="form-actions">
              <el-button type="primary" @click="search" class="cyber-button">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch" class="cyber-button">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="cyber-table-card">
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="user_id" label="用户ID" />
          <el-table-column prop="room_fee" label="房间费用" />
          <el-table-column prop="extra_fee" label="额外费用" />
          <el-table-column prop="bill_time" label="账单时间" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="edit(scope.row)" class="cyber-button">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="del(scope.row)" class="cyber-button danger">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchObj.current"
            v-model:page-size="searchObj.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="Number(total)"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" :title="isAdd ? '新增账单' : '编辑账单'" width="600px" class="cyber-dialog">
      <div class="dialog-glow"></div>
      <el-form :model="obj" label-width="100px" class="edit-form">
        <el-form-item label="用户ID" prop="user_id">
          <el-input v-model="obj.user_id" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="房间费用" prop="room_fee">
          <el-input v-model="obj.room_fee" placeholder="请输入房间费用" />
        </el-form-item>
        <el-form-item label="额外费用" prop="extra_fee">
          <el-input v-model="obj.extra_fee" placeholder="请输入额外费用" />
        </el-form-item>
        <el-form-item label="账单时间" prop="bill_time">
          <el-date-picker
            v-model="obj.bill_time"
            type="date"
            placeholder="请选择账单时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editWinVisible = false" class="cyber-button">取消</el-button>
          <el-button type="primary" @click="save" class="cyber-button primary">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.cyber-container {
  padding: 20px;
  min-height: calc(100vh - 40px);
  position: relative;
  overflow-y: auto;
}

.cyber-card {
  background: rgba(20, 20, 40, 0.7);
  border-radius: 12px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  border: 1px solid rgba(0, 243, 255, 0.2);
  backdrop-filter: blur(5px);
  position: relative;
  margin-bottom: 20px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(0, 243, 255, 0.2);
  background: rgba(15, 15, 30, 0.8);
  flex-shrink: 0;
}

.card-header h2 {
  color: #00f3ff;
  font-size: 22px;
  margin: 0;
  text-shadow: 0 0 10px rgba(0, 243, 255, 0.5);
}

.cyber-form-card {
  padding: 20px;
  background: rgba(25, 25, 45, 0.6);
  margin: 20px;
  border-radius: 8px;
  border: 1px solid rgba(0, 243, 255, 0.1);
  flex-shrink: 0;
}

.cyber-table-card {
  padding: 0 20px 20px;
  flex: 1;
  overflow-y: auto;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.search-form .el-input__wrapper {
  background: rgba(10, 10, 25, 0.5);
  border: 1px solid rgba(0, 243, 255, 0.3);
  box-shadow: 0 0 5px rgba(0, 243, 255, 0.2);
}

.search-form .el-input__wrapper.is-focus {
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.4);
}

.form-actions {
  display: flex;
  justify-content: flex-start;
  gap: 15px;
  margin-top: 10px;
}

.cyber-button {
  background: rgba(50, 50, 80, 0.7);
  border: 1px solid rgba(0, 243, 255, 0.5);
  color: #00f3ff;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.cyber-button:hover {
  background: rgba(0, 243, 255, 0.2);
  box-shadow: 0 0 15px rgba(0, 243, 255, 0.4);
  border-color: #00f3ff;
}

.cyber-button.primary {
  background: linear-gradient(90deg, #00f3ff, #00aaff);
  border: 1px solid #00f3ff;
  color: #000;
  font-weight: 600;
}

.cyber-button.primary:hover {
  background: linear-gradient(90deg, #00aaff, #00f3ff);
  box-shadow: 0 0 20px rgba(0, 243, 255, 0.6);
}

.cyber-button.danger {
  background: linear-gradient(90deg, #ff0055, #ff0000);
  border: 1px solid #ff0055;
  color: #fff;
}

.cyber-button.danger:hover {
  background: linear-gradient(90deg, #ff0000, #ff0055);
  box-shadow: 0 0 20px rgba(255, 0, 85, 0.6);
}

.cyber-table-card :deep(.el-table) {
  background: rgba(20, 20, 40, 0.7);
  border: 1px solid rgba(0, 243, 255, 0.2);
  color: #e0e0ff;
}

.cyber-table-card :deep(.el-table__header th) {
  background: rgba(15, 15, 30, 0.9);
  color: #00f3ff;
  font-weight: 600;
}

.cyber-table-card :deep(.el-table__row:hover) {
  background: rgba(0, 243, 255, 0.1);
}

.cyber-table-card :deep(.el-table__row) {
  background: rgba(25, 25, 45, 0.5);
}

.cyber-table-card :deep(.el-table__cell) {
  border-color: rgba(0, 243, 255, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  flex-shrink: 0;
}

.cyber-dialog :deep(.el-dialog) {
  background: rgba(20, 20, 40, 0.95);
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #00f3ff;
  box-shadow: 0 0 30px rgba(0, 243, 255, 0.3);
  backdrop-filter: blur(10px);
  position: relative;
}

.dialog-glow {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, transparent, #00f3ff, #ff00ff, transparent);
  z-index: 10;
}

.cyber-dialog :deep(.el-dialog__header) {
  background: rgba(10, 10, 25, 0.9);
  color: #ffffff;
  padding: 18px 20px;
  border-bottom: 1px solid rgba(0, 243, 255, 0.3);
  position: relative;
}

.cyber-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
  text-shadow: 0 0 5px rgba(0, 243, 255, 0.7);
}

.edit-form {
  padding: 20px;
}

.edit-form :deep(.el-form-item__label) {
  color: #00f3ff;
  text-shadow: 0 0 5px rgba(0, 243, 255, 0.5);
}

.edit-form :deep(.el-input__wrapper) {
  background: rgba(10, 10, 25, 0.5);
  border: 1px solid rgba(0, 243, 255, 0.3);
  box-shadow: 0 0 5px rgba(0, 243, 255, 0.2);
}

.edit-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.4);
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 10px;
}
</style>
